package com.resign.carl.iterator.api.impl;

import com.resign.carl.iterator.entity.MenuItem;

import java.util.Iterator;

/**
 * Created by carl.zhao on 2016/6/16.
 */
public class DinerMenuIterator implements Iterator<MenuItem> {
    private MenuItem[] menuItems;
    int position = 0;
    public DinerMenuIterator(MenuItem[] items){
        this.menuItems = items;
    }

    @Override
    public boolean hasNext() {
        if(null == menuItems || position >= menuItems.length || null == menuItems[position]){
            return false;
        }
        return true;
    }

    @Override
    public MenuItem next() {
        MenuItem result = menuItems[position];
        position++;
        return result;
    }

    @Override
    public void remove() {
        if(position <= 0){
            throw new IllegalStateException("You can't remove an item util you're done at least one next()");
        }
        if(null != menuItems[position - 1]){
            for(int i = position - 1; i < (menuItems.length - 1); i++){
                menuItems[i] = menuItems[i + 1];
            }
            menuItems[menuItems.length - 1] = null;
        }
    }
}
